package com.camus.algorithm.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.camus.algorithm.SubsetAlgorithm4Int;

/**
 * 递归优化(有大量重复元素的场景)算法求目标和的子集
 * 
 * @author jie.deng
 *
 */
public class SubsetAlgorithmOfDistinctRecursion4Int implements SubsetAlgorithm4Int {
	
	private static final Logger log = LoggerFactory.getLogger(SubsetAlgorithmOfDistinctRecursion4Int.class);

	@Override
	public int[] findSubsetOfTargetSum(int[] candidateArr, int target) {
		counter.remove();

		// 消重，记录重复元素的索引
		// K=num V=index
		Map<Integer, List<Integer>> indexListMap = new HashMap<>();
		for (int i = 0; i < candidateArr.length; i++) {
			List<Integer> indexList = indexListMap.get(candidateArr[i]);
			if (indexList == null) {
				indexList = new ArrayList<>();
				indexListMap.put(candidateArr[i], indexList);
			}
			indexList.add(i);
		}

		// 准备消重后的numArr
		int distinctNumSize = indexListMap.keySet().size();
		int[] distinctNumArr = new int[distinctNumSize];
		for (Integer num : indexListMap.keySet()) {
			distinctNumArr[--distinctNumSize] = num;
		}

		// 逐层递归
		int[] subsetArr = findSubsetOfTargetSum(candidateArr, target, new boolean[candidateArr.length], distinctNumArr,
				0, indexListMap, 0);

		log.info("入参paramArr={},target={},resultArr={},时间复杂度={}", Arrays.toString(candidateArr), target, subsetArr,
				counter.get());
		return subsetArr == null || subsetArr.length == 0 ? null : subsetArr;
	}

	/**
	 * 
	 * @param candidateArr
	 * @param target
	 * @param flagArr
	 * @param distinctNumArr
	 * @param nextIdx
	 * @param indexListMap
	 * @param curSum
	 * @return
	 */
	public int[] findSubsetOfTargetSum(int[] candidateArr, int target, boolean[] flagArr, int[] distinctNumArr,
			int nextIdx, Map<Integer, List<Integer>> indexListMap, int curSum) {
		counter.set(counter.get().intValue() + 1);
		// 递归终止条件
		if (curSum == target) {
			return filterSubset(candidateArr, flagArr);
		}
		if (nextIdx >= distinctNumArr.length) {
			return null;
		}

		// 处理当前层逻辑
		int distinctNum = distinctNumArr[nextIdx];
		List<Integer> idxList = indexListMap.get(distinctNum);
		// 对于本层的distinctNum，有idxList.size()+1种选择：
		// 1.包含0个distinctNum 2.包含1个distinctNum...n.包含所有的distinctNum
		for (int size = 0; size <= idxList.size(); size++) {
			// process current logic
			for (int idx = 0; idx < size; idx++) {
				flagArr[idxList.get(idx)] = true;
			}

			// drill down
			int[] result = findSubsetOfTargetSum(candidateArr, target, flagArr, distinctNumArr, nextIdx + 1,
					indexListMap, curSum + distinctNum * size);
			if (result != null) {
				return result;
			}

			// restore current status
			for (int idx = 0; idx < size; idx++) {
				flagArr[idxList.get(idx)] = false;
			}
		}
		return null;
	}

	private int[] filterSubset(int[] candidateArr, boolean[] flagArr) {
		int len = candidateArr.length;

		int size = 0;
		for (int i = 0; i < len; i++) {
			if (flagArr[i]) {
				size++;
			}
		}

		int[] subsetArr = new int[size];
		for (int i = len - 1; i >= 0; i--) {
			if (flagArr[i]) {
				subsetArr[--size] = candidateArr[i];
			}
		}
		return subsetArr;
	}

}
